package com.abc.easyclaim;

import java.util.Date;
import java.util.ArrayList;

import com.abc.tool.StringTool;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.hardware.Camera;
import android.hardware.Camera.AutoFocusCallback;
import android.hardware.Camera.PictureCallback;
import android.hardware.Camera.ShutterCallback;

public class CameraPreview extends Activity{
	SurfaceView sView;
	SurfaceHolder surfaceHolder;
	Camera camera;          //定义系统所用的照相机
	boolean isPreview=false;              //是否在预览中
	int screenWidth,screenHeight;            //屏幕的宽和高
	Button takephotoButton;          //照相按钮
	Button backButton;              //返回按钮
	private String commentString;      //照片评论字符串
	private String photoNameString;    //照片名称字符串
	private Date photoDate;           //拍照日期
	private int currentPhoto=0;           //当前照片是第几张
	private boolean retakePhoto=false;    //是否是重新拍照的标记
	private ArrayList<String> photoNameStrings=new ArrayList<String>();     //照片名称集合
	private byte[] photoData;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		//设置竖屏
		this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
		//设置无标题
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		//设置全屏
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.camera_preview);
		//获取窗口管理器
		WindowManager wManager =getWindowManager();
		Display display =wManager.getDefaultDisplay();
		DisplayMetrics metrics =new DisplayMetrics();
		//获取屏幕的宽和高
		display.getMetrics(metrics);
		screenWidth=metrics.widthPixels;
		screenHeight=metrics.heightPixels;
		//获取界面中组件
		sView=(SurfaceView)findViewById(R.id.mySurfaceView);
		takephotoButton=(Button)findViewById(R.id.takephoto);
		backButton=(Button)findViewById(R.id.back);
		//获取Camera传过来的数据
		Bundle bundle=this.getIntent().getExtras();         //获取数据对象
		photoNameStrings=bundle.getStringArrayList("photoNameStrings");
		currentPhoto=bundle.getInt("currentPhoto");
		retakePhoto=bundle.getBoolean("retakephoto", false);
		//获得SurfaceView的SurfaceHolder
		surfaceHolder=sView.getHolder();
		//为surfaceHolder添加一个回调监听器
		surfaceHolder.addCallback(new Callback() {
			
			@Override
			public void surfaceDestroyed(SurfaceHolder holder) {
				// TODO Auto-generated method stub
				//释放摄像头
				if(camera!=null)
				{
					if(isPreview)
					{
						camera.stopPreview();    //停止预览
					}
					camera.release();
					camera=null;
				}
			}
			
			@Override
			public void surfaceCreated(SurfaceHolder holder) {
				// TODO Auto-generated method stub
				//打开摄像头
				initCamera();
			}
			
			@Override
			public void surfaceChanged(SurfaceHolder holder, int format, int width,
					int height) {
				// TODO Auto-generated method stub
				
			}
		});
		//为拍照按钮添加监听器
		takephotoButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if(camera!=null && isPreview)
				{
					//控制摄像头自动对焦后才拍照
					camera.autoFocus(autoFocusCallback);
				}
			}
		});	
		//为返回按钮添加监听器
		backButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
			}
		});		
	}
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}
	
	//初始化相机方法
	private void initCamera() {
		if (camera==null && !isPreview) {             //如果不在预览中，且摄像头没打开，则打开摄像头
			camera=Camera.open();
			//camera.setDisplayOrientation(90);
		}
		if (camera!=null && !isPreview) {
			try {
				//通过SurfaceView显示取景画面
				camera.setPreviewDisplay(surfaceHolder);
				//开始预览
				camera.startPreview();
				
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}
			isPreview=true;
		}	
	}
	
	AutoFocusCallback autoFocusCallback=new AutoFocusCallback() {
		//自动对焦时激发该方法
		@Override
		public void onAutoFocus(boolean success, Camera camera) {
			// TODO Auto-generated method stub
			if (success) {
				camera.takePicture(myShutterCallback, myRawCallback, myjpegCallback);
				isPreview=false;
			}
		}
	};
	
	//快门回调接口，当用户按下快门时激发该监听器
	ShutterCallback myShutterCallback=new ShutterCallback() {
		
		@Override
		public void onShutter() {
			// TODO Auto-generated method stub
			
		}
	};
	//拍照回调接口，当相机获取原始照片时激发该监听器
	PictureCallback myRawCallback=new PictureCallback() {
		
		@Override
		public void onPictureTaken(byte[] data, Camera camera) {
			// TODO Auto-generated method stub
			
		}
	};
	//拍照回调接口，当相机获取JPEG照片时激发该监听器
	PictureCallback myjpegCallback=new PictureCallback() {
		
		@Override
		public void onPictureTaken(final byte[] data, Camera camera) {
			// TODO Auto-generated method stub		
			photoDate=new Date(System.currentTimeMillis());//获取当前时间 
			//不是重新拍照
			if (!retakePhoto) {
				Intent intent=new Intent(CameraPreview.this,PhotoComment.class);
				Bundle bundle=new Bundle();
				bundle.putByteArray("data", data);             //传入图片数据
				bundle.putStringArrayList("photoNameStrings", photoNameStrings);  //传入照片名称集合用于判断是否重名
				currentPhoto=photoNameStrings.size();
				bundle.putInt("currentPhoto", currentPhoto);              //传入当前是第几张照片
				bundle.putString("photoDate", StringTool.date2String(photoDate, "yyyy-MM-dd HH:mm:ss"));
				bundle.putBoolean("isreedit", false);          //传入是否是重新编辑的标记
				intent.putExtras(bundle);
				startActivityForResult(intent, 2);	
			}
			//重新拍照
			else {
				getIntent().putExtra("pic", data);
				getIntent().putExtra("retakephoto", retakePhoto);
				//返回拍照日期
				getIntent().putExtra("photoDate", StringTool.date2String(photoDate, "yyyy-MM-dd HH:mm:ss"));
				getIntent().putExtra("currentPhoto", currentPhoto);
				setResult(20, getIntent());        //如果是重新拍照，数据返回到Camera界面
				finish();
			}
		}
	};

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		if (resultCode==10) {
			//接收PhotoComment返回的数据
			photoData=data.getByteArrayExtra("pic");
			commentString=data.getStringExtra("comment");
			photoNameString=data.getStringExtra("name");
			String photoDate=data.getStringExtra("photoDate");
			Boolean isreedit=data.getBooleanExtra("isreedit", false);
			data.getExtras().remove("pic");
			data.getExtras().remove("comment");
			data.getExtras().remove("name");
			data.getExtras().remove("photoDate");
			data.getExtras().remove("isreedit");
			System.gc();
			
			//向Camera界面传回数据
			getIntent().putExtra("pic", photoData);    //返回照片
			//返回评论内容
			getIntent().putExtra("comment", commentString);
			//返回照片名称
			getIntent().putExtra("name", photoNameString);
			//传回拍照日期
			getIntent().putExtra("photoDate", photoDate);
			//传回是否是重新编辑的标记
			getIntent().putExtra("isreedit", isreedit);
			//返回当前页面
			System.out.println("currentPhoto="+currentPhoto);
			getIntent().putExtra("currentPhoto", currentPhoto);
			setResult(20, getIntent());
			finish();
		} 
			
		super.onActivityResult(requestCode, resultCode, data);
	}
	
	
}
